<?php

namespace common\models\member;

use common\models\bonus\Bonus;
use common\models\forms\CreditsLogForm;
use Yii;
use yii\db\ActiveRecord;
use yii\web\NotFoundHttpException;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%level_order}}".
 *
 * @property int $id
 * @property int $member_id
 * @property int $before_level
 * @property string $amount
 * @property int $created_at
 * @property int $after_level
 * @property int $status
 */
class LevelOrder extends ActiveRecord
{

    /**
     * @return array
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
            ],
        ];
    }
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%level_order}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['member_id',  'after_level'], 'required'],
            [['member_id', 'before_level', 'created_at', 'after_level', 'status'], 'integer'],
            [['amount'], 'number'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'member_id' => Yii::t('app', 'Member ID'),
            'before_level' => Yii::t('app', '升级前'),
            'amount' => Yii::t('app', '金额'),
            'created_at' => Yii::t('app', 'Created At'),
            'after_level' => Yii::t('app', '升级后'),
            'status' => Yii::t('app', 'Status'),
        ];
    }

    public function getMember()
    {
        return $this->hasOne(Member::class,['id'=>'member_id']);
    }

    public function buyLevel()
    {   
        $member         = Member::findOne($this->member_id);
        $after_level    = $this->after_level;
        $before_level   = $member->current_level;
        $old_level_model = Level::find()->where(['level'=> $before_level])->one();
        $new_level_model = Level::find()->where(['level'=> $after_level])->one();
        $this->before_level = $before_level;
        if($after_level <= $before_level){
            return $this->addError('after_level',Yii::t('app', '无需升级'));
        }
        $this->amount = $new_level_model->money - $old_level_model->money;
        $member->current_level = $after_level;
        // 写入当前会员
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if($this->save() && $member->update()){
                Yii::$app->services->member->set($member);
                // 变动积分/余额
                Yii::$app->services->memberCreditsLog->decrMoney(new CreditsLogForm([
                    'member' => Yii::$app->services->member->get($member->id),
                    'num' => $this->amount,
                    'credit_group' => 'frontend',
                    'remark' => !empty($this->remark) ? $this->remark : '会员主动购买',
                ]));
                // 累加投资额度
                Member::updateAllCounters(['my_amount' => $this->amount], ['id' => $member->id]);
                // 添加团队业绩，和检测级别一起
                $ids = $member->getAllParentsId();
                if ($ids) {
                    Member::updateAllCounters(['team_amount' => $this->amount], ['in', 'id', $ids]);
                }
                //推荐奖
                Bonus::referralBonus($member,$this->amount);
                $transaction->commit();
                return true;
            }else{
                $transaction->rollBack();
                throw new NotFoundHttpException(Yii::t('app', '消费失败'));
            }
        } catch (NotFoundHttpException $e) {
            $transaction->rollBack();
            $this->addError('after_level', $e->getMessage());
            return false;
        }
    }
}
